package cn.com.startai.smartadh5.main.view;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;

import com.orhanobut.logger.Logger;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import cn.com.startai.smartadh5.R;
import cn.com.startai.smartadh5.db.db.entity.PlayInfo;
import cn.com.startai.smartadh5.db.sp.SPManager;
import cn.com.startai.smartadh5.extension.utils.LogUtil;
import cn.com.startai.smartadh5.extension.utils.UriUtil;
import cn.com.startai.smartadh5.main.fragment.VideoFragment;
import cn.com.startai.smartadh5.processlogic.entity.bean.player.PlayLoopModeBean;

/**
 * @author 尹晓童
 *         邮箱：yinxtno1@yeah.net
 *         时间：2018/1/22
 *         作用：视频播放器
 */

public class SimpleVideoView extends StandardGSYVideoPlayer {

    //    private ImageView ivPlay;
    //播放列表
    private List<PlayInfo> playList = new ArrayList<>();
    //当前播放位置
    private int mCurPosition = -1;
    private PlayInfo mCurPlayInfo;
    //播放模式
    private int mLoopMode = PlayLoopModeBean.MODE_LOOP;

    private int currentTime;
    private boolean isCallCompletionMethod = false;

    private OnPlayStateChangeListener mPlayStateChangedListener;
    private OnProgressChangeListener mProgressChangeListener;
    private View mStart;

    public SimpleVideoView(Context context, Boolean fullFlag) {
        super(context, fullFlag);
    }

    public SimpleVideoView(Context context) {
        super(context);
    }

    public SimpleVideoView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void init(Context context) {
        super.init(context);
        initView();
//        ivPlay.setSelected(false);
    }

    @Override
    public int getLayoutId() {
        return R.layout.video_layout;
    }

    private void initView() {
//        ivPlay = (ImageView) findViewById(R.id.iv_play);
        mStart = findViewById(R.id.start);
    }

    /**
     * 设置循环模式
     *
     * @param loopMode
     */
    public void setLoopMode(int loopMode) {
        mLoopMode = loopMode;
    }

    /**
     * 点击播放控件
     **/
    public void getClickStart() {
        mStart.setSoundEffectsEnabled(false);
        mStart.performClick();
    }


    private boolean setUpWrapper(String url, boolean cacheWithPlay, File cachePath, String title) {
        return setUp(UriUtil.parseUrl(url), cacheWithPlay, cachePath, title);
    }

    /**
     * setUp
     *
     * @param playInfoList
     * @param cacheWithPlay
     * @param position
     * @param cachePath
     * @return
     */
    public boolean setUp(List<PlayInfo> playInfoList, boolean cacheWithPlay, int position, File cachePath) {
        if (playInfoList == null || playInfoList.isEmpty()) {
            return false;
        }
        release();

        boolean set;
        this.playList.clear();
        this.playList.addAll(playInfoList);
        this.mCurPosition = position;
        this.mCurPlayInfo = playInfoList.get(position);


        set = setUpWrapper(mCurPlayInfo.getFilePath(), cacheWithPlay, cachePath, mCurPlayInfo.getFileName());
        if (!TextUtils.isEmpty(mCurPlayInfo.getFileName())) {
            mTitleTextView.setText(mCurPlayInfo.getFileName());
        }
        return set;
    }

    /**
     * 设置指定内容，如果该内容没有存在播放列表中，就加入到播放列表
     *
     * @param playInfo
     * @param cacheWithPlay
     * @param cachePath
     * @return
     */
    public boolean setUp(PlayInfo playInfo, boolean cacheWithPlay, File cachePath) {
        if (playInfo == null) {
            return false;
        }
        release();
        boolean set;
        int position;
        if ((position = playList.indexOf(playInfo)) == -1) {
            for (int i = 0; i < playList.size(); i++) {
                PlayInfo temp = playList.get(i);
                if (playInfo.getFileId().equals(temp.getFileId())) {
                    position = i;
                    break;
                }
            }
            if (position == -1) {
                playList.add(playInfo);
                position = playList.size() - 1;
            }
        }
        this.mCurPlayInfo = playInfo;
        this.mCurPosition = position;
        set = setUpWrapper(playInfo.getFilePath(), cacheWithPlay, cachePath, playInfo.getFileName());
        if (!TextUtils.isEmpty(playInfo.getFileName())) {
            mTitleTextView.setText(playInfo.getFileName());
        }
        return set;
    }

    /**
     * 添加播放列表
     *
     * @param playInfoList
     */
    public void addList(List<PlayInfo> playInfoList) {
        if (playInfoList == null || playInfoList.isEmpty()) {
            return;
        }
        this.playList.addAll(playInfoList);
    }


    @Override
    public void onAutoCompletion() {
        release();
        switch (SPManager.getInstance().getCurrentLoopMode()) {
            default:
            case PlayLoopModeBean.MODE_LOOP:
                mCurPosition = (++mCurPosition) % playList.size();
                mCurPlayInfo = playList.get(mCurPosition);
                break;
            case PlayLoopModeBean.MODE_SINGLE_CYCLE:
                mCurPlayInfo = playList.get(mCurPosition);
                break;
            case PlayLoopModeBean.MODE_RANDOM:
                mCurPosition = new Random().nextInt(playList.size());
                mCurPlayInfo = playList.get(mCurPosition);
                break;
        }
        resetPlay(mCurPlayInfo, mCache, mCachePath, mCurPlayInfo.getFileName(), 1000);
    }

    @Override
    public void onCompletion() {
        if (isCallCompletionMethod) {
            super.onCompletion();
            isCallCompletionMethod = false;
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        super.onProgressChanged(seekBar, progress, fromUser);
        if (mProgressChangeListener != null) {
            mProgressChangeListener.onProgressChange(getCurrentPlayInfo(), progress);
        }
    }

    @Override
    protected void touchSurfaceMoveFullLogic(float absDeltaX, float absDeltaY) {
        super.touchSurfaceMoveFullLogic(absDeltaX, absDeltaY);
        //不给触摸快进，如果需要，屏蔽下方代码即可
        mChangePosition = false;

        //不给触摸音量，如果需要，屏蔽下方代码即可
        mChangeVolume = false;

        //不给触摸亮度，如果需要，屏蔽下方代码即可
        mBrightness = false;
    }

    @Override
    protected void setStateAndUi(int state) {
        if (mPlayStateChangedListener != null) {
            if (state == CURRENT_STATE_PLAYING) {
                //此处通过 seekBar 获取当前播放进度
                mPlayStateChangedListener.onPlay(getCurrentPlayInfo(), mProgressBar.getProgress());
            } else if (state == CURRENT_STATE_PAUSE || state == CURRENT_STATE_AUTO_COMPLETE || state == CURRENT_STATE_ERROR) {
                mPlayStateChangedListener.onPause(getCurrentPlayInfo(), mProgressBar.getProgress());
            }
        }
        super.setStateAndUi(state);

    }

    @Override
    public void onVideoResume() {
        mPauseBeforePrepared = false;
        if (mCurrentState == CURRENT_STATE_PAUSE) {


            try {
                if (mCurrentPosition > 0 && GSYVideoManager.instance().getMediaPlayer() != null) {
                    long s = mCurrentPosition;
                    Log.i("SimpleVideoView", "mCurrentPosition = " + s);
                    GSYVideoManager.instance().getMediaPlayer().seekTo(mCurrentPosition);
                    GSYVideoManager.instance().getMediaPlayer().start();
                    setStateAndUi(CURRENT_STATE_PLAYING);
                    mCurrentPosition = 0;

                }
            } catch (Exception e) {
                e.printStackTrace();
                if (mCurrentPosition > 0 && mCurPlayInfo != null) {
                    setUp(mCurPlayInfo, mCache, mCachePath);
                    postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            setSeekOnStart(mCurrentPosition);
                            startPlayLogic();
                        }
                    }, 300);
                } else {
                    removeAllPlayList();
                }
            }
        }
    }


    public void next() {
        if (playList.isEmpty()) {
            return;
        }
        int playPosition = mCurPosition;
          if (mLoopMode == PlayLoopModeBean.MODE_RANDOM) {
            mCurPosition = new Random().nextInt(playList.size());
            mCurPlayInfo = playList.get(mCurPosition);
        }else {
            playPosition = (++playPosition) % playList.size();
            mCurPlayInfo = playList.get(playPosition);
        }
        boolean set = resetPlay(mCurPlayInfo, mCache, mCachePath, mCurPlayInfo.getFileName(), 1000);
        if (set) {
            mCurPosition = playPosition;
        }
    }

    public void previous() {
        if (playList.isEmpty()) {
            return;
        }
        int playPosition = mCurPosition;
         if (mLoopMode == PlayLoopModeBean.MODE_RANDOM) {
            mCurPosition = new Random().nextInt(playList.size());
            mCurPlayInfo = playList.get(mCurPosition);
        }else {
            if (playPosition - 1 < 0) {
                playPosition = playList.size() - 1;
            } else {
                playPosition--;
            }
            mCurPlayInfo = playList.get(playPosition);
        }
        boolean set = resetPlay(mCurPlayInfo, mCache, mCachePath, mCurPlayInfo.getFileName(), 1000);
        if (set) {
            mCurPosition = playPosition;
        }
    }

    /**
     * 重新播放
     */
    public boolean resetPlay(PlayInfo info, boolean cacheWithPlay, File cachePath, String title, long delayTime) {
        if (setUpWrapper(info.getFilePath(), cacheWithPlay, cachePath, title)) {
            if (!TextUtils.isEmpty(title)) {
                mTitleTextView.setText(title);
            }

            postDelayed(new Runnable() {
                @Override
                public void run() {

                    setSeekOnStart(0);
                    LogUtil.v(VideoFragment.TAG, " resetPlay startPlayLogic");
                    startPlayLogic();
                    if (mPlayStateChangedListener != null) {
                        mPlayStateChangedListener.onChange(info);
                    }

                }
            }, delayTime);

            return true;
        }
        return false;
    }

    @Override
    protected void changeUiToPauseShow() {
        super.changeUiToPauseShow();
//        setViewShowState(ivPlay, VISIBLE);
//        ivPlay.setSelected(false);
    }

    @Override
    protected void changeUiToPlayingShow() {
        super.changeUiToPlayingShow();
//        setViewShowState(ivPlay, VISIBLE);
//        ivPlay.setSelected(true);
    }

    @Override
    protected void changeUiToNormal() {
        super.changeUiToNormal();
        setViewShowState(mBottomContainer, VISIBLE);
//        setViewShowState(ivPlay, VISIBLE);

        mProgressBar.setProgress(0);
        mProgressBar.setSecondaryProgress(0);
        mCurrentTimeTextView.setText("00:00");
        mTotalTimeTextView.setText("00:00");
//        ivPlay.setSelected(false);
        mTitleTextView.setText("");
    }

    @Override
    protected void hideAllWidget() {
        super.hideAllWidget();
//        setViewShowState(ivPlay, INVISIBLE);
    }

    public List<PlayInfo> getPlayList() {
        return playList;
    }

    public PlayInfo getCurrentPlayInfo() {
        return mCurPlayInfo;
    }

    /**
     * 删除单个播放记录
     *
     * @param removedPosition 需要删除音乐的 position
     * @return 删除后的列表集合
     */
    public void removePlayInfo(int removedPosition) {
        if (mCurPosition == removedPosition && playList.size() == 1) {
            removeAllPlayList();
        } else if (mCurPosition == removedPosition) {
            playList.remove(removedPosition);
            mCurPosition--;
            next();
        } else if (removedPosition <= playList.size() - 1) {
            PlayInfo info = playList.remove(removedPosition);
            Logger.d("sssssssssss==============>" + info);
        }
    }

    public void removeAllPlayList() {
        isCallCompletionMethod = true;
        playList.clear();
        //删除全部
        mCurPosition = -1;
        mCurPlayInfo = null;
        onVideoReset();
        this.release();
        if (mPlayStateChangedListener != null) {
            mPlayStateChangedListener.onEmpty();
        }
    }

    @Override
    protected void setProgressAndTime(int progress, int secProgress, int currentTime, int totalTime) {
        super.setProgressAndTime(progress, secProgress, currentTime, totalTime);
        this.currentTime = currentTime;
    }


    public int getCurrentTime() {
        return currentTime;

    }

    public interface OnProgressChangeListener {
        void onProgressChange(PlayInfo info, int progress);
    }

    public interface OnPlayStateChangeListener {

        void onChange(PlayInfo info);

        void onPlay(PlayInfo info, int progress);

        void onPause(PlayInfo info, int progress);

        /**
         * 播放列表被清空
         */
        void onEmpty();
    }

    public void setOnPlayStateChangeListener(OnPlayStateChangeListener l) {
        mPlayStateChangedListener = l;
    }

    public void setOnProgressChangeListener(OnProgressChangeListener l) {
        mProgressChangeListener = l;
    }
}
